<template>
  <div class="ctcPage">
    <Head
      :lang = "lang"
      :pairInfo = "pairInfo"
      :pair = "pair"
      :coinList = "coinList"
      @switchCurrency = "switchCurrency"
    ></Head>

    <section class="ctcMargin" id="pageBody">
      <div class="nav">
        <h3 style="font-size:30px; color:#ccc; text-align:center; margin-top:-60px; line-height:60px;">C2C</h3>
        <ul>
          <li v-for="(item, index) in coinList">
            <span>
              <img :src="currencyImgUrl + item.Logo"/> {{item.CoinCode}}
            </span>
            <a v-for="currencyCode in item.CurrencyList" @click="switchCurrency(item.CoinCode, currencyCode.CurrencyCode, item.Precision, currencyCode.Precision)"
              :class="{active : pair.coinCode === item.CoinCode &&　pair.currencyCode === currencyCode.CurrencyCode}">
              {{currencyCode.CurrencyCode}}
            </a>
          </li>
          <li><router-link class="link" to="/assets/remitInfo?assetsCode=USD">{{lang['C2C USD Deposit']}}</router-link></li>
          <li><router-link class="link" to="/assets/remitInfo?assetsCode=HKD">{{lang['C2C HKD Deposit']}}</router-link></li>
        </ul>
      </div>

      <div class="PageContentRight">
        <div class="available">
          <p><span>{{lang['my singular']}}</span>
            {{orderStat.OrdertotalNum || 0}}
          </p>
          <p><span>{{lang['completion rate']}}</span>
            {{orderStat.CompletionRate * 100 | currency('USD', '', 2) | fillDecimal(2)}}%
          </p>
          <p><span>{{lang['available']}}</span>
            {{pair.coinCode}}:
            {{formatNum(currentCoinAsset.AvailableAmount, currentCoinAsset.Precision)}}
          </p>

          <p><span>{{lang['freeze']}}</span>
            {{pair.coinCode}}:
            {{formatNum(currentCoinAsset.FreeAmount, currentCoinAsset.Precision)}}
          </p>

          <router-link :to="{path: '/assets', query: {from: $route.name}}">{{lang['recharge']}}</router-link>
        </div>

        <section class="section1">
          <div class="section1-left">
            <h3 class="title">{{pair.coinCode}}/{{pair.currencyCode}} {{lang['index number']}}</h3>
            <div class="newPrice" :class="pairInfo.Rose >= 0 ? 'green' : 'red'">
              {{pairInfo.CurrentPrice | currency('USD', '', pair.cyPrec) | fillDecimal(pair.cyPrec)}}
              {{pair.currencyCode}}
              <span>
                {{pairInfo.LatestPrice || 0 | currency('USD', '', pair.cyPrec) | fillDecimal(pair.cyPrec)}}
                <img src="./images/rise.png" v-show="pairInfo.Rose >= 0">
                <img src="./images/fall.png" v-show="pairInfo.Rose < 0">
                (<font v-html="pairInfo.Rose >= 0 ? '+' : ''"></font>{{(pairInfo.Rose * 100) || 0 | currency('USD', '', 2) | fillDecimal(2)}}%)
              </span>
            </div>

            <div class="lowHeight">
              <p>
                24h {{lang['highest']}}
                <span> {{pairInfo.HighestPrice | currency('USD', '', pair.cyPrec) | fillDecimal(pair.cyPrec)}} {{pair.currencyCode}}</span>
              </p>
              <p>
                24h {{lang['lowest']}}
                <span>{{pairInfo.LowestPrice | currency('USD', '', pair.cyPrec) | fillDecimal(pair.cyPrec)}} {{pair.currencyCode}}</span>
              </p>
            </div>

            <Chart
              :lang="lang"
              :pair = "pair"
            ></Chart>
          </div>

          <div class="sectionRightMainAAA" ref="sectionRightMainAAA">

          <div class="sectionRightMain" ref="sectionRightMain">
          <div class="releaseTransaction" ref="releaseTransaction">
                <p class="left">
                  <!-- <a class="isOnlineOnly" :class="{active: isOnlineOnly }" @click="isOnlineOnly = !isOnlineOnly">{{lang['display only online']}}</a> -->
                  <a class="obtain" href="https://goo.gl/forms/Q34tVfxlAg6rNyE03" target="_blank" v-show="langKey === 'zh-CN'">{{lang['obtain V certification']}}</a>
                  <a class="obtain" href="https://goo.gl/forms/PGW8fPCdN1QItnFq2" target="_blank" v-show="langKey !== 'zh-CN'">{{lang['obtain V certification']}}</a>
                </p>
                <p class="right">
                  {{lang['the price is not appropriate']}}
                  <a @click="showPostAdBox()">{{lang['issue a trade order']}}</a>
                </p>
              </div>
            <section class="section1-right" ref="sectionRight">

              <!-- 广告买卖列表  -->
              <div style="position: relative;" ref="adListWrap">
                <div class="advertisementList" ref="adList" style="position: absolute;width: 100%;">
                  <div class="thead">
                    <div class="td client" :style="{width: advertisementList.client}">{{lang['seller']}}</div>
                    <div class="td textRight" :style="{width: advertisementList.orderNumber}">{{lang['odd number']}}</div>
                    <div class="td textRight" :style="{width: advertisementList.completionRate}">{{lang['completion rate']}}</div>
                    <div class="td textRight" :style="{width: advertisementList.ofPayment}">
                      <p>{{lang['mode of payment']}}</p>
                    </div>
                    <div class="td textRight" :style="{width: advertisementList.quantity}">{{lang['quantity']}} ({{pair.coinCode}})</div>
                    <div class="td textRight" :style="{width: advertisementList.price}">{{lang['price']}} ({{pair.currencyCode}})</div>
                  </div>

                  <div class="tbody" ref="tbody" style="position: relative; z-index: 0; ">
                    <div style="position: relative;z-index: 2;">

                      <div class="tr" v-for="item in adList" v-if="(item.TradeSide === 1) && (item.UseQuantity > 0)">
                        <div class="td" :style="{width: advertisementList.client}">
                          <div class="merchantOnline">
                            <img src="./images/online.png">
                          </div>
                          <div class="merchantCertification">
                            <p :title="item.RealName">{{item.RealName}}</p>
                            <img :src="'/static/images/ctc/cer' + langKey + '.png'">
                            <img :src="'/static/images/ctc/bail' + langKey + '.png'" v-if="!item.AcceptedWarranty && (item.EnsureAmount > 0)">
                            <img :src="'/static/images/ctc/bail2' + langKey + '.png'" v-if="item.AcceptedWarranty && (item.EnsureAmount > 0)">
                          </div>
                        </div>

                        <div class="td textRight" :style="{width: advertisementList.orderNumber}">
                          {{item.CustomerInfoDTO ? item.CustomerInfoDTO.OrdertotalNum : 0 }}
                        </div>
                        <div class="td textRight" :style="{width: advertisementList.completionRate}">
                          {{item.CustomerInfoDTO ? calcFinishingRate(item.CustomerInfoDTO.CompletionRate, 100) : 0 | fillDecimal(2)}}%
                        </div>
                        <div class="td textRight" :style="{width: advertisementList.ofPayment}">
                          <img :src="'/static/images/ctc/Bank' + pair.currencyCode + '.png'" v-if="item.HasBank">
                          <img :src="'/static/images/ctc/Alipay' + pair.currencyCode + '.png'" v-if="item.HasAlipay && (pair.currencyCode !== 'VND')">
                          <img :src="'/static/images/ctc/WebChat' + pair.currencyCode + '.png'" v-if="item.HasWeChat && (pair.currencyCode !== 'VND')">
                        </div>

                        <div class="td textRight" :style="{width: advertisementList.quantity}">
                          <p>
                            {{item.UseQuantity | currency('USD', '', pair.coinPrec) | fillDecimal(pair.coinPrec)}}
                          </p>
                        </div>

                        <div class="td red textRight" :style="{width: advertisementList.price}">
                          {{item.Price | currency('USD', '', pair.cyPrec) | fillDecimal(pair.cyPrec)}}
                        </div>

                        <div class="td" :style="{width: advertisementList.operate}">
                          <button type="button" @click="showBuyBox(item)" v-show="mixUserInfo.userId !== item.UserID">{{lang['buy for a rise']}}</button>
                          <button type="button" class="blue" @click="cancelOrder(item, 1)" v-show="mixUserInfo.userId === item.UserID">
                            {{lang['cancelBth']}}
                          </button>
                          <button type="button" class="blue marginLeft" @click="showModifyAdBox(item, true)"  v-show="mixUserInfo.userId === item.UserID">
                            {{lang['basic_revise']}}
                          </button>
                        </div>
                      </div>

                      <div class="oneDayMarket" v-show="adList.length" ref="adListLine"> </div>

                      <div class="tr" v-for="item in adList" v-if="(item.TradeSide === 0) && (item.UseQuantity > 0)">
                        <div class="td" :style="{width: advertisementList.client}">
                          <div class="merchantOnline">
                            <img src="./images/online.png">
                          </div>
                          <div class="merchantCertification">
                            <p>{{item.RealName}}</p>
                            <img :src="'/static/images/ctc/cer' + langKey + '.png'">
                          </div>
                        </div>

                        <div class="td textRight" :style="{width: advertisementList.orderNumber}">
                          {{item.CustomerInfoDTO ? item.CustomerInfoDTO.OrdertotalNum : 0 }}
                        </div>
                        <div class="td textRight" :style="{width: advertisementList.completionRate}">
                          {{item.CustomerInfoDTO ? calcFinishingRate(item.CustomerInfoDTO.CompletionRate, 100) : 0 | fillDecimal(2)}}%
                        </div>
                        <div class="td textRight" :style="{width: advertisementList.ofPayment}">
                          <img :src="'/static/images/ctc/Bank' + pair.currencyCode + '.png'" v-if="item.HasBank">
                          <img :src="'/static/images/ctc/Alipay' + pair.currencyCode + '.png'" v-if="item.HasAlipay && (pair.currencyCode !== 'VND')">
                          <img :src="'/static/images/ctc/WebChat' + pair.currencyCode + '.png'" v-if="item.HasWeChat && (pair.currencyCode !== 'VND')">
                        </div>

                        <div class="td textRight" :style="{width: advertisementList.quantity}">
                          <p>
                            {{item.UseQuantity | currency('USD', '', pair.coinPrec) | fillDecimal(pair.coinPrec)}}
                          </p>
                        </div>

                        <div class="td green textRight" :style="{width: advertisementList.price}">
                          {{item.Price | currency('USD', '', pair.cyPrec) | fillDecimal(pair.cyPrec)}}
                        </div>

                        <div class="td" :style="{width: advertisementList.operate}">
                          <button type="button" class="red"  @click="showSellBox(item)"  v-show="mixUserInfo.userId !== item.UserID">
                            {{lang['offtake']}}
                          </button>
                          <button type="button" class="blue" @click="cancelOrder(item, 1)" v-show="mixUserInfo.userId === item.UserID">
                            {{lang['cancelBth']}}
                          </button>
                          <button type="button" class="blue marginLeft" @click="showModifyAdBox(item, false)" v-show="mixUserInfo.userId === item.UserID">
                            {{lang['basic_revise']}}
                          </button>
                        </div>
                      </div>
                    </div>

                    <div style="position: absolute; z-index: 1; left: 0; top: 0; width: 100%;" v-show="adList2.length">

                      <div class="tr" v-for="item in adList2" v-if="(item.TradeSide === 1) && (item.UseQuantity > 0)">
                        <div class="td" :style="{width: advertisementList.client}">
                          <div class="merchantOnline">
                            <img src="./images/online.png">
                          </div>
                          <div class="merchantCertification">
                            <p>{{item.RealName}}</p>
                            <img :src="'/static/images/ctc/cer' + langKey + '.png'">
                            <img :src="'/static/images/ctc/bail' + langKey + '.png'" v-if="!item.AcceptedWarranty && (item.EnsureAmount > 0)">
                            <img :src="'/static/images/ctc/bail2' + langKey + '.png'" v-if="item.AcceptedWarranty && (item.EnsureAmount > 0)">
                          </div>
                        </div>

                        <div class="td textRight" :style="{width: advertisementList.orderNumber}">
                          {{item.CustomerInfoDTO ? item.CustomerInfoDTO.OrdertotalNum : 0 }}
                        </div>
                        <div class="td textRight" :style="{width: advertisementList.completionRate}">
                        {{item.CustomerInfoDTO ? calcFinishingRate(item.CustomerInfoDTO.CompletionRate, 100) : 0 | fillDecimal(2)}}%
                        </div>
                        <div class="td textRight" :style="{width: advertisementList.ofPayment}">
                          <img :src="'/static/images/ctc/Bank' + pair.currencyCode + '.png'" v-if="item.HasBank">
                          <img :src="'/static/images/ctc/Alipay' + pair.currencyCode + '.png'" v-if="item.HasAlipay && (pair.currencyCode !== 'VND')">
                          <img :src="'/static/images/ctc/WebChat' + pair.currencyCode + '.png'" v-if="item.HasWeChat && (pair.currencyCode !== 'VND')">
                        </div>

                        <div class="td textRight" :style="{width: advertisementList.quantity}">
                          <p>
                            {{item.UseQuantity | currency('USD', '', pair.coinPrec) | fillDecimal(pair.coinPrec)}}
                          </p>

                        </div>

                        <div class="td red textRight" :style="{width: advertisementList.price}">
                          {{item.Price | currency('USD', '', pair.cyPrec) | fillDecimal(pair.cyPrec)}}
                        </div>

                        <div class="td" :style="{width: advertisementList.operate}">
                          <button type="button" v-show="mixUserInfo.userId !== item.UserID">{{lang['buy for a rise']}}</button>
                          <button type="button" class="blue" v-show="mixUserInfo.userId === item.UserID">
                            {{lang['cancelBth']}}
                          </button>
                          <button type="button" class="blue marginLeft" v-show="mixUserInfo.userId === item.UserID">
                            {{lang['basic_revise']}}
                          </button>
                        </div>
                      </div>

                      <div class="oneDayMarket" v-show="adList2.length"> </div>

                      <div class="tr" v-for="item in adList2" v-if="(item.TradeSide === 0) && (item.UseQuantity > 0)">
                        <div class="td" :style="{width: advertisementList.client}">
                          <div class="merchantOnline">
                            <img src="./images/online.png">
                          </div>
                          <div class="merchantCertification">
                            <p>{{item.RealName}}</p>
                            <img :src="'/static/images/ctc/cer' + langKey + '.png'">
                          </div>
                        </div>

                        <div class="td textRight" :style="{width: advertisementList.orderNumber}">
                          {{item.CustomerInfoDTO ? item.CustomerInfoDTO.OrdertotalNum : 0 }}
                        </div>
                        <div class="td textRight" :style="{width: advertisementList.completionRate}">
                          {{item.CustomerInfoDTO ? calcFinishingRate(item.CustomerInfoDTO.CompletionRate, 100) : 0 | fillDecimal(2)}}%
                        </div>
                        <div class="td textRight" :style="{width: advertisementList.ofPayment}">
                          <img :src="'/static/images/ctc/Bank' + pair.currencyCode + '.png'" v-if="item.HasBank">
                          <img :src="'/static/images/ctc/Alipay' + pair.currencyCode + '.png'" v-if="item.HasAlipay && (pair.currencyCode !== 'VND')">
                          <img :src="'/static/images/ctc/WebChat' + pair.currencyCode + '.png'" v-if="item.HasWeChat && (pair.currencyCode !== 'VND')">
                        </div>

                        <div class="td textRight" :style="{width: advertisementList.quantity}">
                          <p>
                            {{item.UseQuantity | currency('USD', '', pair.coinPrec) | fillDecimal(pair.coinPrec)}}
                          </p>
                        </div>

                        <div class="td green textRight" :style="{width: advertisementList.price}">
                          {{item.Price | currency('USD', '', pair.cyPrec) | fillDecimal(pair.cyPrec)}}
                        </div>

                        <div class="td" :style="{width: advertisementList.operate}">
                          <button type="button" class="red" v-show="mixUserInfo.userId !== item.UserID">
                            {{lang['offtake']}}
                          </button>
                          <button type="button" class="blue" v-show="mixUserInfo.userId === item.UserID">
                            {{lang['cancelBth']}}
                          </button>
                          <button type="button" class="blue marginLeft" v-show="mixUserInfo.userId === item.UserID">
                            {{lang['basic_revise']}}
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>

              </div>
              </div>
            </section>
          </div>
          </div>
        </section>

        <!-- 订单列表 -->
        <!--@resizeAdListScroll = "resizeAdListScroll" -->
        <CustomerOrder
          :lang="lang"
          :userInfo="mixUserInfo"
          :currentFeeConfig = "currentFeeConfig"
          :feeConfigs = "feeConfigs"
          :pair = "pair"
          :getSettingInfo = "getSettingInfo"
          :mixUserInfo = "mixUserInfo"
          @getAdList = "getAdList"
          @refreshCurrentAdList = "refreshCurrentAdList"
        ></CustomerOrder>

      </div>
    </section>

    <!-- 发布交易 -->
    <PostAdBox
      :lang="lang"
      :propIsShowPostAdBox.sync = "isShowPostAdBox"
      :customerVerification = "customerVerification"
      :currentCoinAsset = "currentCoinAsset"
      :currentFeeConfig = "currentFeeConfig"
      :pair = "pair"
      :getPayTypeList = "getPayTypeList"
      :payList = "payList"
      :pairInfo = "pairInfo"
      :getCustomerInfoList = "getCustomerInfoList"
      :getKYCRuleList = "getKYCRuleList"
      @getCustomerInfo = "getCustomerInfo"
      @refreshCurrentAdList = "refreshCurrentAdList"
    ></PostAdBox>

    <!-- 买卖币 -->
    <TradeBox
      :lang="lang"
      :propIsShowTradeBox.sync = "isShowTradeBox"
      :isBuyOrSell = "isBuyOrSell"
      :customerVerification = "customerVerification"
      :currentCoinAsset = "currentCoinAsset"
      :currentOrder = "currentOrder"
      :currentFeeConfig = "currentFeeConfig"
      :pair = "pair"
      :pairInfo = "pairInfo"
      :getCustomerInfoList = "getCustomerInfoList"
      @refreshCurrentAdList = "refreshCurrentAdList"
    ></TradeBox>

    <!-- 修改交易 -->
    <ModifyAdBox
      :lang="lang"
      :propIsShowModifyAd.sync = "isShowModifyAdBox"
      :isModifyBuyOrSell = "isModifyBuyOrSell"
      :currentCoinAsset = "currentCoinAsset"
      :currentFeeConfig = "currentFeeConfig"
      :currentModifyOrder = "currentModifyOrder"
      :pair = "pair"
      :pairInfo = "pairInfo"
      :getCustomerInfoList = "getCustomerInfoList"
      @refreshCurrentAdList = "refreshCurrentAdList"
    ></ModifyAdBox>

    <PageFooter2 :lang="lang" :langKey="langKey"></PageFooter2>
  </div>
</template>

<script>
import commonMixins from '@/mixins/common.js'
import ModalApi from '@/components/SwModal/api.js'
import PostAdBox from './components/PostAdBox.vue'
import TradeBox from './components/TradeBox.vue'
import CustomerOrder from './components/CustomerOrder.vue'
import ModifyAdBox from './components/ModifyAdBox.vue'
import Chart from './components/Chart.vue'
import Head from './components/Head.vue'

import commonFilter from '@/filters/common.js'
import CodeHandles from '@/service/Http/codeHandles.js'
import EventBus from '@/service/EventBus.js'
import Decimal from '@/libs/decimal.min.js'
import Utils from '@/utils/Utils.js'
import LocalStorage from '@/utils/LocalStorage.js'

import $ from 'jquery'

export default {
  mixins: [commonMixins],
  data () {
    return {
      advertisementList: {  // 广告列表宽度
        // client: '12%',
        // orderNumber: '8%',
        // completionRate: '13%',
        // ofPayment: '17%',
        // quantity: '12%',
        // price: '15%',
        // operate: '23%'
      },
      isShowPostAdBox: false,  // 控制发布广告弹窗
      isShowTradeBox: false,  // 买币买币弹窗提示层 开关
      isShowModifyAdBox: false,  // 控制发布广告弹窗
      isBuyOrSell: false, // false 买币 true 卖币
      isModifyBuyOrSell: false, // false 买币 true 卖币
      currentOrder: {}, // 买卖币当前列表
      coinList: [], // 币种列表信息
      assetsData: {},  // 资产信息
      adList: [], // 订单数组
      adList2: [],
      customerVerification: [], // 用户凭证数组
      currentCoinAsset: {},
      isOnlineOnly: false,
      feeConfigs: {},
      currentFeeConfig: {},
      c2cTimer: null,
      isDisablePostAd: false,
      currentModifyOrder: {},
      pair: {},
      pairInfo: {}, // 获取最新价 24小时最高 最低价
      orderStat: {}, //  获取完成完成率 和完成单数
      lastScrollTop: 0,
      getPayTypeList: {},
      payList: {},
      getCustomerInfoList: {},
      getKYCRuleList: {},
      getSettingInfo: {}
    }
  },
  components: {
    PostAdBox,
    TradeBox,
    CustomerOrder,
    ModifyAdBox,
    Chart,
    Head
  },
  watch: {
    // 广告列表 滚动条兼容
    langKey () {

    },
    adList () {
      this.resizeAdListHeight()
    }
  },
  methods: {
    calcFinishingRate (a, b) {
      a = new Decimal(a || 0)
      return a.mul(b || 0).toFixed(10)
    },
    // 发布交易
    showPostAdBox () {
      if (!this.mixUserInfo.token) {
        let that = this
        let handle = CodeHandles['51001']({
          ok () {
            handle.close()
            that.$router.push({path: '/user/login', query: {from: that.$route.name}})
          }
        })
        return
      }
      this.getCustomerInfo()
      .then((res) => {
        this.getCustomerInfoList = res.Data || {}
      })

      this.$host2.get('Collection/GetPayTypeList', {
        currencyCode: this.pair.currencyCode
      }, {
        isQueryString: true
      }).then((res) => {
        if (res.StatusCode === '200') {
          this.getPayTypeList = res.Data || {}
        }
      })

      this.$host2.post('Collection/PayList', {
        currencyCode: this.pair.currencyCode
      }).then((res) => {
        if (res.StatusCode === '200') {
          this.payList = res.Data || {}
          this.isShowPostAdBox = true
        }
      })
    },
    // 获取保证金 违约金
    getCustomerInfo () {
      return this.$host2.post('CustomerInfo/GetCustomerInfo', {
        coinCode: this.pair.coinCode
      }, {
        ignorableCodes: '51077'
      })
    },
    // 修改发布交易
    showModifyAdBox (item, value) {
      this.currentModifyOrder = item
      this.isModifyBuyOrSell = value // value 等于 true 修改买单 false 修改卖单
      this.getCustomerInfo()
      .then((res) => {
        this.getCustomerInfoList = res.Data || {}
      })
      this.isShowModifyAdBox = true
    },
    verifyResult (number) {
      // 筛选是否需要身份认证
      let IsEnaled =''
      for (let i=0; i < this.getKYCRuleList.length; i++) {
        if (this.getKYCRuleList[i].ConstraintRange === number) {
          IsEnaled = this.getKYCRuleList[i].IsEnaled
        }
      }
      // 判断是否需要认证
      if (IsEnaled && this.customerVerification.VerifyResult !== 2) {
        let content;
        let okText = "to authenticate";
        if (this.customerVerification.VerifyResult === 0) {
          content = "c2c sell buy real name authentication"; // '您还没有实名认证，不能交易',
        }
        if (this.customerVerification.VerifyResult === 1) {
          content = "c2C your real name certification failed"; // "您的实名认证未通过，请重新认证"
        }
        if (this.customerVerification.VerifyResult === 3) {
          // 您的实名认证正在审核中，请耐心等待'
          content = "42075";
          okText = "determineBth";
        }
        
        let that = this
        let handle = ModalApi.confirm({
          isShowCloseBtn: true,
          isCloseOnClickBg: true,
          modalClass: "commonModal smallModal",
          title: "prompt message",
          content: content,
          noText: "", // '取消',
          okText: okText, // '去认证',
          isShowBg: true,
          ok: () => {
            // 审核中不需要跳去认证
            that.customerVerification.VerifyResult !== 3 && that.$router.push({ path: "/safety?isToggleCaidVerified=true" });
            handle.close();
          }
        });
        return false
      }
      return true
    },
    // 买币
    showBuyBox (e) {
      if (!this.mixUserInfo.token) {
        let that = this
        let handle = CodeHandles['51001']({
          ok () {
            handle.close()
            that.$router.push({path: '/user/login', query: {from: that.$route.name}})
          }
        })
        return
      }

      // 身份认证判断
      if (!this.verifyResult(6)) {return}

      this.isBuyOrSell = false // 显示买币元素
      this.currentOrder = e
      this.lockOrderPrice(e)

      this.getCustomerInfo()
      .then((res) => {
        if (res.StatusCode === '200') {
          this.getCustomerInfoList = res.Data || {}

          if (e.AcceptedWarranty && !this.getCustomerInfoList.WithoutBondCanBuy) {
            let content
            if (this.getCustomerInfoList.CancelCountBy24H >= 3) {
              content = this.lang['c2c 3 cancellations by unsecured buyers within 24 hours']
                .replace('{time}', this.getSettingInfo.CancelHour || 0)
                .replace('{count}', this.getSettingInfo.MaxAllowCancelCount || 0)
              // '无保证金买家24小时内取消3次,不得下单'
            } else {
              content = this.lang['c2c margin buyers do not limit the number of transaction orders']
                .replace('{time}', this.getSettingInfo.CancelHour || 0)
                .replace('{count}', this.getSettingInfo.MaxAllowCancelCount || 0)
              // 无保证金买家24小时内下单数不得超过3单（不含已完成）'
            }
            let confirm = ModalApi.confirm({
              isShowCloseBtn: true,
              isCloseOnClickBg: true,
              modalClass: 'commonModal smallModal',
              content: content,
              okText: 'determineBth',
              noText: '',
              title: 'prompt message',
              isShowBg: true,
              ok () {
                confirm.close()
              }
            })
          } else if (!e.AcceptedWarranty && !this.getCustomerInfoList.WithBondCanBuy) {
            // let depositAmount = commonFilter.currency(commonFilter.ceilDecimal(this.getCustomerInfoList.Deposit, this.getCustomerInfoList.DepositPrecision) || 0, 'USD', '', this.getCustomerInfoList.DepositPrecision)

            // depositAmount = commonFilter.fillDecimal(depositAmount, this.getCustomerInfoList.DepositPrecision)

            let handle = ModalApi.confirm({
              modalClass: 'commonModal',
              isShowCloseBtn: true,
              isCloseOnClickBg: true,
              title: 'prompt message',
              content: () => {
                return this.lang['the account balance is lower than']
                  .replace('{DepositAmount}', this.currentFeeConfig.DepositAmount || 0)
              },
              noText: '',  // '取消',
              okText: 'recharge', // '充值',
              isShowBg: true,
              ok: () => {
                this.$router.push({path: '/assets'})
                handle.close()
              }
            })
          } else {
            this.isShowTradeBox = true
          }
        }
      })
    },
    // 卖币
    showSellBox (e) {
      if (!this.mixUserInfo.token) {
        let that = this
        let handle = CodeHandles['51001']({
          ok () {
            handle.close()
            that.$router.push({path: '/user/login', query: {from: that.$route.name}})
          }
        })
        return
      }
      // 身份认证判断
      if (!this.verifyResult(7)) {return}

      // 判断是否绑定手机号
      if (!this.customerVerification.IsBindingPhone) {
        let handle = ModalApi.confirm({
          isShowCloseBtn: true,
          isCloseOnClickBg: true,
          modalClass: 'commonModal smallModal',
          title: 'prompt message',
          content: 'you are not yet bound to the phone', // '该账号没有绑定手机号',
          noText: '', // '取消'
          okText: 'bindings', // '去绑定',
          isShowBg: true,
          ok: () => {
            this.$router.push({path: '/safety?isTogglePhone=true'})
            handle.close()
          }
        })
        return
      }
      // 判断是否设置收款信息
      if (!this.customerVerification.IsSetReceiveAccount) {
        let handle = ModalApi.confirm({
          isShowCloseBtn: true,
          isCloseOnClickBg: true,
          modalClass: 'commonModal smallModal',
          title: 'prompt message',
          content: 'You have not set up the collection information', // '您尚未设置收款信息!',
          noText: '', // '取消'
          okText: 'set up', // '设置',
          isShowBg: true,
          ok: () => {
            this.$router.push({path: '/assets/bankcard'})
            handle.close()
          }
        })
        return
      }
      this.isBuyOrSell = true // 显示卖币元素
      this.currentOrder = e
      this.lockOrderPrice(e)

      this.$host2.post('SellOut/CheckPayType', {
        orderId: e.ID
      }).then((res) => {
        if (res.StatusCode === '200') {
          this.isShowTradeBox = true
        }
      })
    },
    // 价格锁定接口
    lockOrderPrice (item) {
      this.$host2.post('Order/LockOrder', {
        orderId: item.ID
      }).then((res) => {
        let Price = res.Data.TradingPrice || ''
        this.$set(this.currentOrder, 'newPrice', Price)
      })
    },
    // 取消广告单
    cancelOrder (item, type) {
      let that = this
      let confirm = ModalApi.confirm({
        isShowCloseBtn: true,
        isCloseOnClickBg: true,
        modalClass: 'commonModal smallModal',
        content: 'whether to cancel', // '是否取消',
        okText: 'determineBthAD',
        noText: 'cancelBthAD',
        title: 'cancellation of order point out',
        isShowBg: true,
        ok () {
          if (that.isDisablePostAd) { return }
          that.isDisablePostAd = true
          this.$host2.post('Order/CancelOrder', {
            id: item.ID,
            cancelType: type
          }).then((res) => {
            if (res.StatusCode === '200') {
              ModalApi.message(that.lang['cancel success'])
              confirm.close()
              setTimeout(() => {
                that.refreshCurrentAdList()
                EventBus.$emit('refreshMyOrderList')
              }, 1000)
            }
            that.isDisablePostAd = false
          })
        }
      })
    },
    // 切换币种列表
    switchCurrency (coinCode, currencyCode, coinPrec, cyPrec) {
      this.pair.coinCode = coinCode
      this.pair.currencyCode = currencyCode
      this.pair.coinPrec = coinPrec
      this.pair.cyPrec = cyPrec
      LocalStorage.set('currentPair', this.pair)
      this.switchCoin()
    },
    switchCoin () {
      this.getAsset()
      this.getOrderStat() // 获取完成完成率 和完成单数
      this.getAdList() // 获取广告单列表
      this.getCurrentFeeConfig() // 获取费率配置
      this.getPairInfo() // 获取最新价 24小时最高最低价 涨跌幅度
      this.getCustomerVerification() // 获取用户凭证信息

      let pairStr = this.pair.coinCode + '_' + this.pair.currencyCode
      // 修改路由的coin参数
      history.replaceState(null, '', '/fiat/index/' + pairStr)
      // 存本地
      Utils.LS.set('ctcPair', pairStr)
    },
    getCurrentCoinAsset (code) {
      if (!this.assetsData.Assets) {
        return
      }
      for (let i = 0; i < this.assetsData.Assets.length; i++) {
        if (this.assetsData.Assets[i].AssetsCode === code) {
          this.currentCoinAsset = this.assetsData.Assets[i]
        }
      }
    },
    formatNum (val, pre) {
      return commonFilter.fillDecimal(commonFilter.currency(new Decimal(val || 0).toFixed(10), 'USD', '', pre), pre)
    },
    getAsset () {
      let p = Utils.makePromise()

      this.mixUserInfo.userName && this.$http.post('CustomerAssets/GetAssets', {
      }, {
        isDisposeCode: false
      }).then((res) => {
        this.assetsData = res.Data || {} // 资产信息
        this.getCurrentCoinAsset(this.pair.coinCode) // 筛选当前资产数据
        p.resolveHandle(res)
      })

      !this.mixUserInfo.userName && p.resolveHandle({})

      return p
    },
    // 获取用户凭证信息
    getCustomerVerification () {
      this.$host2.post('CustomerVerification/GetCustomerVerification', {
        currencyCode: this.pair.currencyCode
      }, {
        isDisposeCode: false
      }).then((res) => {
        this.customerVerification = res.Data || {}
      })
    },
    // 获取广告列表
    getAdList () {
      this.$host2.post('Order/GetSaleOrderList', {
        CoinCode: this.pair.coinCode, // 虚拟币 Code
        CurrencyCode: this.pair.currencyCode,  // 法币 Code
        pageIndex: 0,
        pageSize: 200
      }, {
        isDisposeCode: false
      })
      .then((res) => {
        if (res.isOk) {
          this.adList = res.Data || []

          // 重叠遮闪
          this.$nextTick(() => {
            this.adList2 = []
          })

          this.setScroll()
          this.resizeAdListScroll()
        } else {
          this.adList = []
        }
      })
    },
    resizeAdListScroll () {
      this.$nextTick(() => {
        this.$body = $(this.$refs.tbody).niceScroll().resize()

        let height = this.$refs.adList.offsetHeight + 5
        let height2 = this.$refs.adList.offsetHeight + this.$refs.releaseTransaction.offsetHeight + 5
        this.$refs.sectionRightMainAAA.style.height = height2 + 'px'
        this.$refs.sectionRightMain.style.height = height2 + 'px'
        this.$refs.sectionRight.style.height = height + 'px'

        $('.section1-right').niceScroll({
          autohidemode: false
        }).resize()

        // 还原上次滚动条位置
        this.lastScrollTop && this.$body.setScrollTop(this.lastScrollTop)
      })
    },
    // 获取所有虚拟币的手续费相关设置信息
    getCurrentFeeConfig () {
      // 若没有找到该币费率，要做容错处理
      this.currentFeeConfig = this.feeConfigs[this.pair.coinCode] || {}
    },
    getFeeConfigs () {
      let p = Utils.makePromise()

      // 只有登录后才有数据
      if (this.mixUserInfo.userName) {
        this.$host2.post('FeeSetting/GetAllFeeSetting', {
        }, {
          isDisposeCode: false
        }).then((res) => {
          this.feeConfigs = res.Data || []
          Utils.definePropertyForArray(this.feeConfigs, 'CoinCode')
          p.resolveHandle(res)
        })
      } else {
        p.resolveHandle()
      }

      return p
    },
    // 获取当前最新价
    getPairInfo () {
      this.$host2.post('TradeConfig/GetC2CPairConfig', {
        sourceCode: this.pair.coinCode, // 虚拟币 Code
        targetCode: this.pair.currencyCode  // 法币 Code
      }, {
        isDisposeCode: false
      }).then((res) => {
        if (res.StatusCode === '200') {
          this.pairInfo = res.Data || {}
        }
      })
    },
    getOrderStat () {
      this.mixUserInfo.userName && this.$host2.post('Order/GetCustomerInfo', {
      }, {
        isDisposeCode: false
      }).then((res) => {
        if (res.StatusCode === '200') {
          this.orderStat = res.Data || {}
        }
      })
    },
    // 当前币种列表
    getCoinList (code) {
      let p = Utils.makePromise()
      this.$host2.post('Order/GetOpenMask', {
      }, {
        isDisposeCode: false
      }).then((res) => {
        this.coinList = res.Data || []
        p.resolveHandle(res)
      })

      return p
    },
    getKYCRule () {
      this.$http.get('Setting/GetKYCRuleList', {
        kYCConstraint: 1
      }, {
        isQueryString: true
      }).then((res) => {
        if (res.StatusCode === '200') {
          this.getKYCRuleList = res.Data || {}
        }
      })
    },
    getC2CSetting () {
      this.$host2.get('Info/GetC2CSetting')
      .then((res) => {
        if (res.StatusCode === '200') {
          this.getSettingInfo = res.Data || {}
        }
      })
    },
    init () {
      Promise.all([this.getC2CSetting(), this.getKYCRule(), this.getFeeConfigs(), this.getCoinList(), this.getAsset()]).then((all) => {
        // 读取本地localPair
        let localPair = Utils.LS.get('ctcPair') || ''
        // 读取url上的urlPair
        let urlPair = this.$route.params.pair || ''
        // urlPair优先于localPair
        let specifiedPair = urlPair || localPair
        specifiedPair = specifiedPair.split('_').length ? specifiedPair.split('_') : null
        let coinCode
        let currencyCode
        let coinPrec
        let cyPrec

        let _currentPair_ = LocalStorage.get('currentPair') || null
        if (_currentPair_) {
          coinCode = _currentPair_.coinCode
          currencyCode = _currentPair_.currencyCode
          coinPrec = _currentPair_.coinPrec
          cyPrec = _currentPair_.cyPrec
        } else {
          if (specifiedPair.length >= 2) {
            coinCode = specifiedPair[0].toUpperCase()
            currencyCode = specifiedPair[1].toUpperCase()
            for (let i = 0; i < this.coinList.length; i++) {
              if (this.coinList[i].CoinCode === coinCode) {
                coinPrec = this.coinList[i].Precision
                cyPrec = this.coinList[i].CurrencyList[0].Precision
                break
              }
            }
          } else {
            coinCode = this.coinList[0].CoinCode
            currencyCode = this.coinList[0].CurrencyList[0].CurrencyCode
            coinPrec = this.coinList[0].Precision
            cyPrec = this.coinList[0].CurrencyList[0].Precision
          }
        }

        this.$set(this.pair, 'coinCode', coinCode) // 当前虚拟币
        this.$set(this.pair, 'currencyCode', currencyCode) // 当前虚拟币法币
        this.$set(this.pair, 'coinPrec', coinPrec) // 当前虚拟币精度
        this.$set(this.pair, 'cyPrec', cyPrec) // 当前法币精度

        this.switchCurrency(this.pair.coinCode, this.pair.currencyCode, this.pair.coinPrec, this.pair.cyPrec)
      })
    },
    setScroll () {
      this.$nextTick(() => {
        //  滚动条居中
        let tbody = this.$refs.tbody
        let $adListLine = $(this.$refs.adListLine)
        if (!$adListLine.length) { return }
        let top = $adListLine.position().top
        if (top > 290) {
          let scrollToHiehgt = top - 290

          tbody.scrollTop = scrollToHiehgt
        } else {
          tbody.scrollTop = 0
        }
      })
    },
    refreshCurrentAdList () {  // 刷新广告列表 当前浮动导航不变
      this.switchCoin()
    },
    resizeAdListHeight () {
      this.$nextTick(() => {
        this.$refs.adListWrap.style.height = this.$refs.adList.offsetHeight + 'px'
      })
    },
    refreshAdList () {
      this.$body && (this.lastScrollTop = this.$body.getScrollTop())
      // 由于vue的数组重新赋值渲染，会先清空节点再显示，所以会出现闪烁，所以进行刷新（即数组赋值）前，在背后加多一层，重叠防闪
      this.adList2 = this.adList
      this.getAdList() // 获取广告单列表
    }
  },
  mounted () {
    this.resizeAdListHeight()
    this.init()
    this.c2cTimer = window.setInterval(() => {
      this.refreshAdList()
      this.getPairInfo() // 获取最新价 24小时最高最低价 涨跌幅度
    }, 1000 * 10)
  },
  beforeRouteLeave (to, from, next) {
    clearInterval(this.c2cTimer)
    $(this.$refs.tbody).remove()
    next()
  }
}
</script>

<style lang="less">
@import './css/index.less';

  .ctcPage .advertisementList .thead .td,
  .ctcPage .advertisementList .tbody .tr .td {
    &:nth-of-type(1) {
      width: 12%!important;
    }
    &:nth-of-type(2) {
      width: 8%!important;
    }
    &:nth-of-type(3) {
      width: 13%!important;
    }
    &:nth-of-type(4) {
      width: 17%!important;
    }
    &:nth-of-type(5) {
      width: 12%!important;
    }
    &:nth-of-type(6) {
      width: 15%!important;
    }
    &:nth-of-type(7) {
      width: 23%!important;
    }
  }
 @media (max-width: 1440px) {
  .ctcPage .ctcMargin .nav {
    width: 136px !important;
  }
  .ctcPage .ctcMargin .nav a {
    text-indent: 1em;
  }
  .ctcPage .PageContentRight {
    margin-left: 156px !important;
  }
  .ctcPage .PageContentRight .section1 .section1-left {
    width:370px;
  }
  .ctcPage .PageContentRight .sectionRightMainAAA {
    margin-left: 380px;
  }
   .ctcPage .PageContentRight .available {
     margin-left: 380px;
   }
  .ctcPage .PageContentRight .available p {
    padding: 0 6px;
  }
  .ctcPage .advertisementList .thead .td,
  .ctcPage .advertisementList .tbody .tr .td {
    &:nth-of-type(1) {
      width: 19%!important;
    }
    &:nth-of-type(2) {
      width: 8%!important;
    }
    &:nth-of-type(3) {
      width: 11%!important;
    }
    &:nth-of-type(4) {
      width: 17%!important;
    }
    &:nth-of-type(5) {
      width: 11%!important;
    }
    &:nth-of-type(6) {
      width: 11%!important;
    }
    &:nth-of-type(7) {
      width: 23%!important;
    }
  }
}

@media screen and (max-width:1200px){
  .ctcPage .ctcMargin {
    min-width:800px;
  }
  /*  // 左侧导航*/
  .ctcPage .ctcMargin .nav {
    width: 200px !important;
  }
  /*  // 折线图 */
  #c2cChart {
    height: 300px !important;
  }
  /*  // 顶部资产显示*/
  .ctcPage .PageContentRight {
    margin-left: 220px !important;
    margin-right:10px;
  }

  .ctcPage .PageContentRight .available {
    margin-left: 0;
    line-height: 30px;
  }
  .ctcPage .PageContentRight .available p {
    text-align: center;
  }
  .ctcPage .PageContentRight .available span {
    display:block;
  }
  /*  // 折线图部分*/

  .ctcPage .PageContentRight .section1 {
    height: auto;
  }

  .ctcPage .PageContentRight .section1 .section1-left {
    position:  relative;
    width: 100%;
    height:490px;
  }

  .ctcPage .PageContentRight .section1 .section1-left .lowHeight:before {
    top: 70px;
  }

  /*  // 广告列表部分*/
  .ctcPage .PageContentRight .sectionRightMainAAA {
    position: relative;
    margin-bottom: 20px;
    margin-left: 0;
  }
  .ctcPage .PageContentRight .section1 .sectionRightMain {
    margin-top: 20px;
    margin-left: 0 ;
    background: #181a23;
  }

  .ctcPage .PageContentRight .releaseTransaction {
    padding: 0 10px;
  }
  .ctcPage .PageContentRight .advertisementList {
    position: absolute;
    width: 100%;
    min-width: 800px;
  }
  .ctcPage .PageContentRight .advertisementList .tbody {
    height: auto !important;
  }
/*  // 订单部分*/
  .ctcPage .orderListWrap .title,
  .ctcPage .orderListWrap .unfilledOrdersList,
  .ctcPage .orderListWrap .completeOrderList {
    min-width: 1400px;
  }

  .ctcPage .orderListWrap .title a{
    min-width: 120px !important;
  }
  .ctcPage .orderListWrap .title a.userguide {
    min-width: auto !important;
    padding-right: 10px !important;
  }
  .ctcPage .orderListWrap {
    padding-top: 20px;
  }
}

  /*  // 订单部分*/

  .ctcPage .orderListWrap {
    position: relative;
  }

  .orderMainAAA {
    width: 100%;
    position: absolute;
  }

  .orderMain {
    position: relative;
  }
</style>

